package com.sgb.kjwl.view.ui.activity.enterprise;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.BR;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.GsonManager;
import com.sgb.kjwl.databinding.ActivityPublishServiceBinding;
import com.sgb.kjwl.di.enterprise.DaggerEnterpriseComponent;
import com.sgb.kjwl.model.entity.ParentAreaMeasureEntity;
import com.sgb.kjwl.model.entity.enterprise.EpQuoteEntity;
import com.sgb.kjwl.model.entity.enterprise.ServiceProjectClassEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.DialogFunction;
import com.sgb.kjwl.utils.DialogHelper;
import com.sgb.kjwl.utils.PointUtils;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.MemberEvent;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.viewmodel.enterprise.PublishServiceActivityModel;
import com.swgk.core.customview.InputFilterUtils;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.zhy.view.flowlayout.TagAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Time:2021/4/15
 * Author:黄淋
 * Description:发布服务页面
 */
public class PublishServiceActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {
    ActivityPublishServiceBinding mBinding;
    PublishServiceActivityModel mModel;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    public static final int REQUEST_CODE_CLSS = 0x0004;
    public static final int REQUEST_CODE_PRICE = 0x0005;
    private Thread thread;
    // 一级联动数据
    private List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>>> typeEntityList;
    // 二级联动数据
    private List<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>> opt2 = new ArrayList<>();
    // 三级联动数据
    private List<List<List<ParentAreaMeasureEntity>>> opt3 = new ArrayList<>();
    private int typePosition1;
    private int typePosition2;
    private int typePosition3;
    private boolean isLoaded = false;
    private String mServiceFirstNo;//服务分类No
    private String mServiceSecondNo;//服务类别No
    private String mServiceThirdNo;//服务类型区No
    private String mServiceFirstName;//服务分类Name
    private String mServiceSecondName;//服务类别Name
    private String mServiceThirdName;//服务类型区Name

    ArrayList<BaseAreaEntity> mCityList;
    Map<String, Object> mMap;
    EpQuoteEntity mEntity;
    String id;
    private boolean isChecked;
    private int selectPosition;


    private OptionsPickerView choceProjectType = null;//选择服务项目

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding.actionBar.setOnBackClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                DialogHelper.showDialog(PublishServiceActivity.this, "温馨提示", "信息还未填写完成，是否离开？", "离开", "继续编辑", new DialogFunction() {
                    @Override
                    public void normalRoundDialog() {

                    }
                }, new DialogFunction() {
                    @Override
                    public void normalRoundDialog() {
                        finish();
                    }
                });

            }
        });
    }

    @Override
    protected void initView() {

        mModel = new ViewModelProvider(this).get(PublishServiceActivityModel.class);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_publish_service);
        mBinding.setVariable(BR.mviewmodel, mModel);
        mBinding.setLifecycleOwner(this);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        mBinding.rlServiceType.setOnClickListener(this);
        mBinding.itvServiceCity.setOnClickListener(this);
        mBinding.itvServiceItem.setOnWholeItemClickListener(this);
        mBinding.itvServiceLabelChoice.setOnWholeItemClickListener(this);
        mBinding.itvServiceLabelPrice.setOnWholeItemClickListener(this);
        mBinding.tvNext.setOnClickListener(this);
        mBinding.llYijia.setOnClickListener(this);

        mBinding.itvContractTelephone.getContent_edt().setInputType(InputType.TYPE_CLASS_PHONE);
        mBinding.itvContractTelephone.setInfilterType(ItemInputTextView.TYPE_PHONE);

        InputFilterUtils.setEditTextInhibitInputSpaChat(mBinding.itvServiceName.getContent_edt(), 30);
        InputFilterUtils.setEditTextInhibitInputSpaChat(mBinding.itvContract.getContent_edt(), 15);

        mBinding.etAddPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable editable) {
                String s = editable.toString();
                mBinding.etAddPrice.removeTextChangedListener(this);

                if (s.contains(".")) {
                    mBinding.etAddPrice.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10 + 3 + 1)});
                    if (s.length() - 1 - s.indexOf(".") > 2) {
                        s = s.substring(0,
                                s.indexOf(".") + 2 + 1);
                        editable.replace(0, editable.length(), s.trim());
                    }
                } else {
                    mBinding.etAddPrice.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10 + 1)});
                    if (s.length() > 10) {
                        s = s.substring(0, 10);
                        editable.replace(0, editable.length(), s.trim());
                    }
                }
                if (s.trim().equals(".")) {
                    s = "0" + s;
                    editable.replace(0, editable.length(), s.trim());
                }

                if (s.startsWith("0") && s.trim().length() > 1) {
                    if (!s.substring(1, 2).equals(".")) {
                        editable.replace(0, editable.length(), "0");
                    }
                }
                mBinding.etAddPrice.addTextChangedListener(this);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {

            }
        });
        mBinding.cityList.setClickable(false);
        mBinding.webDescription.setVisibility(View.GONE);
        mBinding.emptyView.setVisibility(View.VISIBLE);
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void init() {
        mEntity = (EpQuoteEntity) getIntent().getSerializableExtra(RouterKey.DATA);
        if (mEntity != null) {
            mBinding.itvServiceName.setContent(mEntity.getServiceName());
            if (mEntity.getPrice() == -1) {
                isChecked = true;
                mBinding.ivYijia.setSelected(true);
                mBinding.etAddPrice.setEnabled(false);
            } else {
                isChecked = false;
                NumberFormat nf = NumberFormat.getInstance();
                nf.setGroupingUsed(false);
                mBinding.etAddPrice.setText(nf.format(mEntity.getPrice()));
            }
            String subStr = "";
            if (mEntity.getFirstCategoryName() != null && !mEntity.getFirstCategoryName().equals("")) {
                subStr = mEntity.getFirstCategoryName();
                if (mEntity.getSecondCategoryName() != null && !mEntity.getSecondCategoryName().equals("")) {
                    String two = mEntity.getSecondCategoryName();
                    subStr = subStr + "-" + two;
                }
                if (mEntity.getItemName() != null && !mEntity.getItemName().equals("")) {
                    String three = mEntity.getItemName();
                    subStr = subStr + "-" + three;
                }
            }


            if (!TextUtils.isEmpty(mEntity.getProjectClassificationJson())&&!TextUtils.isEmpty(mEntity.getDomesticCompaniesPrice())) {
                mModel.listdata = new Gson().fromJson(mEntity.getProjectClassificationJson(), new TypeToken<List<ServiceProjectClassEntity>>() {
                }.getType());
                mBinding.itvServiceLabelChoice.setContent( mModel.listdata.size() + "个项目分类");
                mBinding.itvServiceLabelPrice.setContent(mEntity.getDomesticCompaniesPrice().equals("-1") ? "议价" : PointUtils.price(Double.parseDouble(mEntity.getDomesticCompaniesPrice())) + "元起");
                mModel.pricelist = new Gson().fromJson(mEntity.getOtherQualificationPrices(), new TypeToken<List<Map<String, Object>>>() {
                }.getType());
                mModel.show_project_type.postValue(true);
                mModel.minPrice = mEntity.getDomesticCompaniesPrice();
                mModel.maxPrice = mEntity.getMaximumPrice();
            } else {
                mModel.show_project_type.postValue(false);
            }

            ArrayList<BaseAreaEntity> cityList = jsonToArrayList(mEntity.getServiceCitys(), BaseAreaEntity.class);
            this.mCityList = cityList;
            mBinding.cityList.setVisibility(View.VISIBLE);
            mBinding.tvChooseCity.setVisibility(View.GONE);
            mBinding.tvMore.setVisibility(cityList.size() > 2 ? View.VISIBLE : View.GONE);

            final LayoutInflater mInflater = LayoutInflater.from(PublishServiceActivity.this);
            List<BaseAreaEntity> cityListShow = cityList.size() > 1 ? cityList.subList(0, 2) : cityList;
            TagAdapter cityAdapter = new TagAdapter<BaseAreaEntity>(cityListShow) {
                @Override
                public View getView(com.zhy.view.flowlayout.FlowLayout parent, int position, BaseAreaEntity entity) {
                    LinearLayout layout = (LinearLayout) mInflater.inflate(R.layout.item_service_part_city, mBinding.cityList, false);
                    TextView tv = layout.findViewById(R.id.tv_info);
                    tv.setText(entity.getName());
                    return layout;
                }
            };
            mBinding.cityList.setAdapter(cityAdapter);

            mBinding.tvChooseServiceType.setText(subStr);
            mBinding.tvChooseServiceType.setTextColor(Color.parseColor("#FF333333"));
            mBinding.itvContract.setContent(mEntity.getContact());
            mBinding.itvContractTelephone.setContent(mEntity.getContactPhone());
//            mBinding.etServiceItem.setEditContent(mEntity.getServiceDetails());
//            mBinding.etServiceDescribe.setEditContent(mEntity.getDescription());
            String content = mEntity.getDescription();
            if (content != null && !content.equals("")) {
                mBinding.webDescription.getSettings().setDefaultTextEncodingName("UTF-8");
                mBinding.webDescription.getSettings().setJavaScriptEnabled(true);//支持JS
                String js = "<script type=\"text/javascript\">" +
                        "var imgs = document.getElementsByTagName('img');" + // 找到img标签
                        "for(var i = 0; i<imgs.length; i++){" +  // 逐个改变
                        "imgs[i].style.width = '100%';" +  // 宽度改为100%
                        "imgs[i].style.height = 'auto';" +
                        "}" +
                        "</script>";
                mBinding.webDescription.loadDataWithBaseURL(null, content + js, "text/html", "UTF-8", null);
                mBinding.webDescription.setVisibility(View.VISIBLE);
                mBinding.emptyView.setVisibility(View.GONE);
            } else {
                mBinding.webDescription.setVisibility(View.GONE);
                mBinding.emptyView.setVisibility(View.VISIBLE);
            }
        }
        mMap = new HashMap<>();
        mModel.ldServiceType.observe(this, list -> showAddressPop(setData(list)));
        mModel.ldSaveSuccess.observe(this, this::addSuccess);
        mModel.ldUpdateSuccess.observe(this, a -> updateSuccess());
        mModel.show_project_type.observe(this, type -> {
            mBinding.itvServiceItem.setContent(type ? "自定义服务项目" : "默认服务项目");
        });
        initObserve();
    }

    private void initObserve() {
        mModel.toast.observe(this, s -> MToast.showToast(PublishServiceActivity.this, s));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_next://下一步
                if (!ClickUtils.isDoubleClick()) {
                    checkData();
                }
                break;
            case R.id.ll_yijia://议价
                if (!ClickUtils.isDoubleClick()) {
                    isChecked = !isChecked;
                    if (isChecked) {
                        mBinding.ivYijia.setSelected(true);
                        mBinding.etAddPrice.setEnabled(false);
                        mBinding.etAddPrice.setText("");
//                        mBinding.etAddPrice.setTextColor(getResources().getColor(R.color.color_C0C4CC));
                    } else {
                        mBinding.ivYijia.setSelected(false);
                        mBinding.etAddPrice.setEnabled(true);
//                        mBinding.etAddPrice.setText("");
//                        mBinding.etAddPrice.setTextColor(getResources().getColor(R.color.FF000000));
                    }
                }
                break;
            case R.id.itv_service_city://选择服务城市
                if (!ClickUtils.isDoubleClick()) {
                    PublishServiceCityActivity.start(this, mCityList, 123);
                }
                break;
            case R.id.rl_service_type://选择服务分类
                if (!ClickUtils.isDoubleClick()) {
                    if (typeEntityList != null) {
                        showServiceTypePop("选择服务分类");
                    } else {
                        mModel.getServiceType(PublishServiceActivity.this);
                    }
                }
                break;


        }
    }


    /**
     * 选择服务分类
     *
     * @param title 弹窗标题
     */
    private void showServiceTypePop(String title) {
        CityPickView cityOption = new CityPickBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String areaName = "";
                if (opt3.get(options1).get(options2).get(options3) == null) {
                    areaName = "";
                } else {
                    areaName = opt3.get(options1).get(options2).get(options3).getName();
                    typePosition3 = options3;
                }
                StringBuilder builder = new StringBuilder();
                builder.append(typeEntityList.get(options1).getName());
                if (!opt2.get(options1).get(options2).getName().equals("")) {
                    builder.append("-").append(opt2.get(options1).get(options2).getName());
                }
                if (!areaName.equals("")) {
                    builder.append("-").append(areaName);
                }
                typePosition1 = options1;
                typePosition2 = options2;
                mServiceFirstNo = typeEntityList.get(options1).getId();
                mServiceSecondNo = opt2.get(options1).get(options2).getId();
                mServiceThirdNo = opt3.get(options1).get(options2).get(options3).getId();
                mServiceFirstName = typeEntityList.get(options1).getName();
                mServiceSecondName = opt2.get(options1).get(options2).getName();
                mServiceThirdName = opt3.get(options1).get(options2).get(options3).getName();

                mBinding.tvChooseServiceType.setText(builder.toString());
                mBinding.tvChooseServiceType.setTextColor(Color.parseColor("#FF333333"));

            }
        }).setCancelText("取消").setSubCalSize(15)
                .setTitleText("选择服务分类")
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .setTextColorCenter(Color.parseColor("#ff333333"))
                .setContentTextSize(15)
                .setLineSpacingMultiplier(2.5f)
                .setDividerColor(Color.parseColor("#EDEDED"))
                .build();
        cityOption.setPicker(typeEntityList, opt2, opt3);
        cityOption.setSelectOptions(typePosition1, typePosition2, typePosition3);
        cityOption.show();
    }

    private void checkData() {
        if (TextUtils.isEmpty(mBinding.itvServiceName.getContent().trim())) {
            MToast.showToast(PublishServiceActivity.this, "请输入服务名称");
            return;
        }

        if (TextUtils.isEmpty(mBinding.tvChooseServiceType.getText().toString().trim())) {
            MToast.showToast(PublishServiceActivity.this, "请选择服务分类");
            return;
        } else if (mCityList == null || mCityList.size() == 0) {
            MToast.showToast(PublishServiceActivity.this, "请选择服务城市");
            return;
        } else if (TextUtils.isEmpty(mBinding.itvContract.getContent().trim())) {
            MToast.showToast(PublishServiceActivity.this, "请输入联系人姓名");
            return;
        } else if (TextUtils.isEmpty(mBinding.itvContractTelephone.getContent().trim())) {
            MToast.showToast(PublishServiceActivity.this, "请输入联系电话");
            return;
        } else if (!CheckUtils.isMobileForService(mBinding.itvContractTelephone.getContent().trim())) {
            MToast.showToast(PublishServiceActivity.this, "请输入正确的电话格式");
            return;
        }


        if (mModel.show_project_type.getValue()) {
            if (mModel.listdata.size() == 0) {
                MToast.showToast(PublishServiceActivity.this, "请添加项目分类");
                return;
            }
            if (mModel.pricelist.size() == 0) {
                MToast.showToast(PublishServiceActivity.this, "请输入价格");
                return;
            }

        } else {
            if (TextUtils.isEmpty(mBinding.etAddPrice.getText().toString().trim()) && !mBinding.ivYijia.isSelected()) {
                MToast.showToast(PublishServiceActivity.this, "请输入价格");
                return;
            }
            if (mBinding.etAddPrice.getText().toString().trim().equals("0") || mBinding.etAddPrice.getText().toString().trim().equals("0.0") ||
                    mBinding.etAddPrice.getText().toString().trim().equals("0.00")) {
                MToast.showToast(PublishServiceActivity.this, "服务收费不能为0");
                return;
            }
        }


        mMap.put("serviceName", mBinding.itvServiceName.getContent().trim());
        if (!mModel.show_project_type.getValue()) {
            if (mBinding.ivYijia.isSelected()) {
                mMap.put("servicePrice", "-1");
            } else {
                mMap.put("servicePrice", mBinding.etAddPrice.getText().toString().trim());
            }
            mMap.put("projectClassificationCount", 1);
        } else {
            mMap.put("projectClassificationCount", mModel.pricelist.size());
            mMap.put("projectClassificationJson", new Gson().toJson(mModel.listdata));
            mMap.put("maximumPrice", mModel.maxPrice);
            mMap.put("domesticCompaniesPrice", mModel.minPrice);
            mMap.put("otherQualificationPrices", new Gson().toJson(mModel.pricelist));
        }

        mMap.put("serviceClass", mServiceFirstNo);
        mMap.put("className", mServiceFirstName);

        mMap.put("serviceCategory", mServiceSecondNo);
        mMap.put("categoryName", mServiceSecondName);

        mMap.put("ServiceItem", mServiceThirdNo);
        mMap.put("ItemName", mServiceThirdName);
        mMap.put("serviceCity", new Gson().toJson(mCityList));
        mMap.put("linkMan", mBinding.itvContract.getContent().trim());
        mMap.put("servicePhone", mBinding.itvContractTelephone.getContent().trim());
        mMap.put("serviceDetails", mBinding.itvServiceLabelChoice.getContent());
//        mMap.put("serviceDescription", mBinding.etServiceDescribe.getEditContent().trim());

        int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        mMap.put("publishType", String.valueOf(type));
        String realName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
        mMap.put("realName", realName);
        String phone = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, "");
        mMap.put("userAccount", phone);
        String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        if (type == 1) {
            mMap.put("companyNo", companyNo);
            mMap.put("teamNo", "0");
        } else if (type == 2) {
            mMap.put("teamNo", companyNo);
            mMap.put("companyNo", "0");
        }

        // TODO: 2021/4/19 上传
        if (mEntity != null) {
            mMap.put("id", mEntity.getId());
            this.id = String.valueOf(mEntity.getId());
            mModel.updateService(this, mMap);
        } else if (id != null && !id.equals("")) {
            mMap.put("id", id);
            mModel.updateService(this, mMap);
        } else {
            mModel.saveService(this, mMap);
        }
    }

    /**
     * 添加成功
     */
    public void addSuccess(String id) {
        this.id = id;
        ActivityJump.jumpToActivity(PublishServiceActivity.this, PublishServiceDealedCasesActivity.class, Pair.create("id", id));
    }

    /**
     * 添加成功
     */
    public void updateSuccess() {
        if (id != null && !id.equals("")) {
            ActivityJump.jumpToActivity(PublishServiceActivity.this, PublishServiceDealedCasesActivity.class, Pair.create("id", id));
        }
    }

    public void showAddressPop(List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>>> datas) {
        this.typeEntityList = datas;
        if (isLoaded) {
            showServiceTypePop("选择服务分类");
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(() -> {
                            // 子线程中解析数据
                            initJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showServiceTypePop("选择服务分类");
                    isLoaded = true;
                    thread = null;
                    break;
                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void initJsonData() {
        //城市列表
        List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>> cityList;
        //区域列表
        List<List<ParentAreaMeasureEntity>> areaList;
        ParentAreaMeasureEntity ParentAreaMeasureEntity = new ParentAreaMeasureEntity();
        ParentAreaMeasureEntity.setName("");
        ParentAreaMeasureEntity.setNo("");
        for (int x = 0; x < typeEntityList.size(); x++) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            if (typeEntityList.get(x).getChildren() == null || typeEntityList.get(x).getChildren().size() == 0) {
                List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>> cityList1 = new ArrayList<>();
                cityList1.add(ParentAreaMeasureEntity);
                opt2.add(cityList1);
                List<ParentAreaMeasureEntity> cityAreaList = new ArrayList<>();
                cityAreaList.add(ParentAreaMeasureEntity);
                areaList.add(cityAreaList);

            } else {
                opt2.add(typeEntityList.get(x).getChildren());
                for (int i = 0; i < typeEntityList.get(x).getChildren().size(); i++) {
                    cityList.add(typeEntityList.get(x).getChildren().get(i));
                    List<ParentAreaMeasureEntity> cityAreaList = new ArrayList<>();
                    //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                    if (typeEntityList.get(x).getChildren().get(i).getChildren() == null
                            || typeEntityList.get(x).getChildren().get(i).getChildren().size() == 0) {
                        cityAreaList.add(ParentAreaMeasureEntity);
                    } else {
                        cityAreaList.addAll(typeEntityList.get(x).getChildren().get(i).getChildren());
                    }
                    areaList.add(cityAreaList);
                }
            }
            opt3.add(areaList);

        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }


    public List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>>> setData(List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>>> listDatas) {
        String cityListsStr = GsonManager.getInstance().getGson().toJson(listDatas);
        List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>>> list = GsonManager.getInstance().getGson().fromJson(cityListsStr, new TypeToken<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity<List<ParentAreaMeasureEntity>>>>>>() {
        }.getType());
        ParentAreaMeasureEntity ParentAreaMeasureEntity = new ParentAreaMeasureEntity();
        ParentAreaMeasureEntity.setName("");
        ParentAreaMeasureEntity.setNo("");
//        list.add(0, ParentAreaMeasureEntity);
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getChildren() == null || list.get(i).getChildren().size() == 0)
                continue;
//            list.get(i).getChildren().add(0, ParentAreaMeasureEntity);
            for (int j = 0; j < list.get(i).getChildren().size(); j++) {
                if (list.get(i).getChildren().get(j).getChildren() == null || list.get(i).getChildren().get(j).getChildren().size() == 0)
                    continue;
//                list.get(i).getChildren().get(j).getChildren().add(0, ParentAreaMeasureEntity);
            }
        }
        return list;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        Log.e("onActivityResult", "onActivityResult");

        if (requestCode == 123) {
            if (resultCode == RESULT_OK && intent != null) {
                ArrayList<BaseAreaEntity> cityList = (ArrayList<BaseAreaEntity>) intent.getExtras().getSerializable("cityList");
                List<BaseAreaEntity> cityListShow = (ArrayList<BaseAreaEntity>) intent.getExtras().getSerializable("cityListShow");
                mCityList = new ArrayList<>();
                mCityList = cityList;
                mBinding.cityList.setVisibility(View.VISIBLE);
                mBinding.tvChooseCity.setVisibility(View.GONE);

                if (cityListShow != null && cityListShow.size() > 0) {
                    mBinding.tvMore.setVisibility(View.VISIBLE);
                } else {
                    cityListShow = cityList.size() > 1 ? cityList.subList(0, 2) : cityList;
                    mBinding.tvMore.setVisibility(cityList.size() > 2 ? View.VISIBLE : View.GONE);
                }

                final LayoutInflater mInflater = LayoutInflater.from(PublishServiceActivity.this);
                TagAdapter cityAdapter = new TagAdapter<BaseAreaEntity>(cityListShow) {
                    @Override
                    public View getView(com.zhy.view.flowlayout.FlowLayout parent, int position, BaseAreaEntity entity) {
                        LinearLayout layout = (LinearLayout) mInflater.inflate(R.layout.item_service_part_city, mBinding.cityList, false);
                        TextView tv = layout.findViewById(R.id.tv_info);
                        tv.setText(entity.getName());
                        return layout;
                    }
                };
                mBinding.cityList.setAdapter(cityAdapter);
            }
        }
        if (requestCode == REQUEST_CODE_CLSS) {
            if (resultCode == RESULT_OK && intent != null) {
                mModel.listdata = (List<ServiceProjectClassEntity>) intent.getExtras().getSerializable("data");
                mModel.isupdateProjectClass = intent.getExtras().getBoolean("isupdate", false);
                if (mModel.isupdateProjectClass) {
                    if(  mModel.pricelist==null) {
                        mModel.pricelist = new ArrayList<>();
                    }else {
                        mModel.pricelist.clear();
                    }
                    for (int i = 0; i < mModel.listdata.size(); i++) {
                        mModel.pricelist = mModel.combinationData(mModel.pricelist, mModel.listdata.get(i).getChild(), i + 1);
                    }
                    mBinding.itvServiceLabelPrice.setContent("");
                    mBinding.itvServiceLabelChoice.setContent(mModel.listdata.size() > 0 ? mModel.listdata.size() + "个项目分类" : "");

                }
            }

        }

        if (requestCode == REQUEST_CODE_PRICE) {
            if (resultCode == RESULT_OK && intent != null) {
                mModel.pricelist = (List<Map<String, Object>>) intent.getExtras().getSerializable("data");
                mModel.minPrice = intent.getExtras().getString("mminprice");
                mModel.maxPrice = intent.getExtras().getString("maxprice");
                for (int i = 0; i < mModel.pricelist.size(); i++) {
                    if (!mModel.pricelist.get(i).get("price").equals("-1")) {
                        break;
                    } else if (i == mModel.pricelist.size() - 1) {
                        mModel.maxPrice = "-1";
                        mModel.minPrice = "-1";
                    }
                }
                if ("-1".equals(mModel.maxPrice) && "-1".equals(mModel.minPrice)) {
                    mBinding.itvServiceLabelPrice.setContent("议价");
                } else {
                    mBinding.itvServiceLabelPrice.setContent(PointUtils.price(Double.parseDouble(mModel.minPrice)) + "元起");
                }
            }

        }
    }


    /**
     * @param json
     * @param clazz
     * @return
     */
    public static <T> ArrayList<T> jsonToArrayList(String json, Class<T> clazz) {
        Type type = new TypeToken<ArrayList<JsonObject>>() {
        }.getType();
        ArrayList<T> arrayList = new ArrayList<>();
        try {
            ArrayList<JsonObject> jsonObjects = new Gson().fromJson(json, type);

            for (JsonObject jsonObject : jsonObjects) {
                arrayList.add(new Gson().fromJson(jsonObject, clazz));
            }
        } catch (Exception e) {

        }

        return arrayList;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(MemberEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_PUBLISH_SERVICE_FINISH) {
            finish();
        }
        EventBus.getDefault().removeStickyEvent(event);
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.itv_service_item://选择服务项目


                if (choceProjectType == null) {
                    choceProjectType = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int options2, int options3, View v) {
                            mModel.show_project_type.postValue(mModel.taxt_project_type.get(options1).name.equals("自定义服务项目"));
                            selectPosition = options2;
                        }
                    }).setCancelText("取消").setSubCalSize(15)
                            .setCancelColor(Color.parseColor("#666666"))
                            .setTitleText("")
                            .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                            .setSubmitText("确定")
                            .setSubmitColor(Color.parseColor("#5792FD"))
                            .setTextColorCenter(Color.parseColor("#ff333333"))
                            .setContentTextSize(15)
                            .setLineSpacingMultiplier(2.5f)
                            .setDividerColor(Color.parseColor("#EDEDED"))
                            .setDecorView(getWindow().getDecorView().findViewById(android.R.id.content)).build();
                    choceProjectType.setPicker(mModel.taxt_project_type);
                    choceProjectType.setSelectOptions(selectPosition);
                }
                choceProjectType.show();
                break;

            case R.id.itv_service_label_choice://选择项目分类

                Intent mIntent = new Intent(this, PublishServiceProjectClassListActivity.class);
                mModel.isupdateProjectClass = false;//重置更新标记
                mIntent.putExtra("data", (Serializable) mModel.listdata);
                startActivityForResult(mIntent, REQUEST_CODE_CLSS);
                break;

            case R.id.itv_service_label_price://选择价格

                if (mModel.listdata.size() > 0) {

                    Intent mIntent2 = new Intent(this, PublishServicePriceListActivity.class);
                    mModel.isupdateProjectClass = false;//重置更新标记
                    mIntent2.putExtra("data", (Serializable) mModel.pricelist);
                    startActivityForResult(mIntent2, REQUEST_CODE_PRICE);

                } else {
                    MToast.showLongToast(this, "请先添加项目分类");
                }

                break;

        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
